#!/bin/bash

# Note that we are running sudo'd


### CONFIG
tempBaseDir="/Library/Application Support/com.onefatgiraffe/mailtrackerblocker"
running="${tempBaseDir}/running"
currentMacOSVer="$(sw_vers -productVersion)"
macOSBigSur="11.0"
targetDir=/Library/Mail/Bundles
userAppSupportDir="/Users/${USER}/Library/Application Support"
bigSurBundlesDir="${userAppSupportDir}/Mail/Plug-ins/Bundles/Library/Mail/Bundles"

### UTILITY
mtb_log() {
    echo "[mailtrackerblocker] $@"
}

### MIGRATED MAC SYMLINK FIX
if [[ -L "$targetDir" ]] && [[ ! -w "$targetDir" ]]; then
    mtb_log "$targetDir is a symlink to an unwritable destination. removing..."
    rm "$targetDir"
fi

# Move our temporary installation into the real destination.
mkdir -p "${targetDir}" || exit 1
mtb_log "moving mailbundle to ${targetDir}"
rm -rf "${targetDir}/MailTrackerBlocker.mailbundle"
mv "${tempBaseDir}/MailTrackerBlocker.mailbundle" "${targetDir}/"

### fix bundle permissions
mtb_log "fixing mailbundle permissions"
chown -R "root:admin" "${targetDir}/MailTrackerBlocker.mailbundle"
chmod -h 755 ${targetDir}
chmod -R u=rwX,go=rX "${targetDir}/MailTrackerBlocker.mailbundle"


# macOS 11.0 and up require code signing
# older versions will NOT run if signed so we have to remove the sig
if [ "$(printf '%s\n' "$macOSBigSur" "$currentMacOSVer" | sort -V | head -n1)" != "$macOSBigSur" ]; then
    # xcrun/codesign_allocate errors on some systems so incl. our own unsign tool
    if [[ -e "$tempBaseDir/unsign" ]]; then
        mtb_log "removing signature with unsign"
        "${tempBaseDir}/unsign" ${targetDir}/MailTrackerBlocker.mailbundle/Contents/MacOS/MailTrackerBlocker || exit 1
        mv ${targetDir}/MailTrackerBlocker.mailbundle/Contents/MacOS/MailTrackerBlocker.unsigned ${targetDir}/MailTrackerBlocker.mailbundle/Contents/MacOS/MailTrackerBlocker
    else
        mtb_log "removing signature with codesign"
        codesign --remove-signature $targetDir/MailTrackerBlocker.mailbundle || exit 1
    fi
else
    mtb_log "auto-enabling plugin for $USER (11.x and up only)"

    # if a GUI install (i.e. not a CLI/Homebrew install)
    GUI_INSTALLER_PID=($(pgrep -u "$USER" -f /System/Library/CoreServices/Installer.app/Contents/MacOS/Installer))
    if [ ! -z "$GUI_INSTALLER_PID" ]; then
        # foreground the installer
        osascript -e 'tell application "/System/Library/CoreServices/Installer.app"
        activate
        end tell'
    fi

    osascript -e 'on run argv
    set src to item 1 of argv as POSIX file
    set dst to item 2 of argv as POSIX file
    set appSupportDir to item 3 of argv as POSIX file

    display dialog "If prompted, please allow the installer to use Finder to enable the plugin." buttons {"OK"} default button 1 giving up after 30 with icon caution

    tell application "Finder"
        set folderNames to {"Mail", "Plug-ins", "Bundles", "Library", "Mail", "Bundles"}
        repeat with theFolder in folderNames
            try
                make new folder at appSupportDir with properties {name: theFolder}
            end try
            set appSupportDir to ((appSupportDir as text) & theFolder) as alias
        end repeat

        duplicate src to dst with replacing
    end tell
    end run' "${targetDir}/MailTrackerBlocker.mailbundle" "${bigSurBundlesDir}" "${userAppSupportDir}"
fi

### Show "Manage Plugins"
mtb_log "enable manage plugins for 10.14 and up"
defaults write "/Library/Preferences/com.apple.mail" EnableBundles -bool YES
defaults write com.apple.mail EnableBundles -bool YES

### relaunch mail if it was running before started
if [ -f "$running" ]; then
    mtb_log "Mail.app was running before installation. reopening."
    open -gb com.apple.mail
    rm "$running"
fi

### cleanup
rm "${tempBaseDir}/unsign"

exit 0
